/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2025-02-04 21:05:07
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2025-02-06 12:34:23
 * @FilePath: \jike\src\store\modules\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 和用户相关的状态管理
import { request } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
import { setToken as _setToken, getToken, removeToken} from "../../utils/token";
import { getProfileAPI, loginAPI } from "@/apis/user";

const useStore = createSlice({
    name:'user',
    // 数据状态
    initialState:{
        token:getToken() || '',
        userInfo:{}
    },
    // 同步修改方法
    reducers:{
        setToken(state,action){
            state.token = action.payload
            // localstorage存一份
            _setToken(action.payload)
        },
        setUserInfo(state,action){
            state.userInfo = action.payload
        },
        clearUserInfo(state){
            state.userInfo = {}
            state.token = ''
            removeToken()
        }
    }
})

// 解构出actionCreator
const {setToken,setUserInfo,clearUserInfo} = useStore.actions

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}

// 获取个人信息异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

// 获取reducer函数
const userReducer = useStore.reducer

export {fetchLogin,fetchUserInfo,clearUserInfo}

export default userReducer